package com.topisv.tms.web.notice;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Maps;
import com.topisv.tms.entity.Function;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.notice.Notice;
import com.topisv.tms.entity.notice.NoticeReader;
import com.topisv.tms.entity.stock.instorage.InstorageBill;
import com.topisv.tms.entity.stock.instorage.InstorageUpSubTaskItem;
import com.topisv.tms.service.notice.NoticeService;
import com.topisv.tms.utils.JsonUtil;
import com.topisv.tms.web.base.BaseDataTableController;

/**
 * 公告管理的Controller, 使用Restful风格的Urls:
 * 
 * 
 * @author 
 */
@Controller
@RequestMapping(value = "/notice")
public class NoticeController extends BaseDataTableController{
	protected Logger log = LoggerFactory.getLogger(getClass());
	private static Map<String, String> sortTypes = Maps.newLinkedHashMap();
	static {
		sortTypes.put("auto", "自动");
		sortTypes.put("showname", "功能名称");
	}
    private String uploadContentType; // 文件类型  

	@Autowired
	private NoticeService noticeService;

	@RequestMapping(value = "v2_show")
	public String list() {
		return "notice/noticeList";
	}
	
	@RequestMapping(value = "page",method = RequestMethod.POST)
	public void page(@RequestBody JSONParam[] paramJson, HttpServletRequest request,HttpServletResponse response){
		try {
			// 客户端参数
			QueryParamHolder paramHolder = collectParam(paramJson);
			Page<Notice> page = noticeService.getNotice(paramHolder);
			// 封装查询结果
			response.getWriter().print(bulidJSON(page));
		} catch (Exception e) {
			
		}
	}
	
	@RequestMapping(value = "v2_create", method = RequestMethod.GET)
	public String createForm(Model model) {
		model.addAttribute("notice", new Notice());
		model.addAttribute("action", "v2_commit");
		return "notice/noticeForm";
	}
	/** 
     * 图片上传 
     *  
     * @return 
     * @throws IOException 
	 * @throws FileUploadException 
     */
	@RequestMapping(value = "ckeditorUpload", method = RequestMethod.POST)
	public String ckeditorUpload(String CKEditor,String CKEditorFuncNum,String langCode,HttpServletResponse response,HttpServletRequest request) throws IOException, FileUploadException{  
        response.setCharacterEncoding("utf-8");  
        PrintWriter out = response.getWriter();  
        ResourceBundle bundle = ResourceBundle.getBundle("notice");  
        boolean isMultipart = ServletFileUpload.isMultipartContent(request) ;
        if(!isMultipart){
        	return null; 
        }
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
        @SuppressWarnings("unchecked")
		List<FileItem> fileitem = servletFileUpload.parseRequest(request);
        if (null == fileitem || 0 == fileitem.size()) {
            return null;
        }
        String fileClientName ="" ;
        Iterator<FileItem> fileitemIndex = fileitem.iterator();
        if (fileitemIndex.hasNext()) {
            FileItem file = fileitemIndex.next();
            
            if (file.isFormField()) {
                System.out.println("Illegal upload ！isFormField=true");
            }
            uploadContentType = file.getContentType() ;
            fileClientName = file.getName() ;
            DiskFileItem item = (DiskFileItem) file ;
            if (!item.isFormField()) {
                fileClientName = item.getStoreLocation().getPath() ;
            }
            
        }
        String callback = CKEditorFuncNum;  
        String expandedName = ""; // 文件扩展名  
        if (uploadContentType.equals("image/pjpeg")  
                || uploadContentType.equals("image/jpeg")) {  
            // IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg  
            expandedName = ".jpg";  
        } else if (uploadContentType.equals("image/png")  
                || uploadContentType.equals("image/x-png")) {  
            // IE6上传的png图片的headimageContentType是"image/x-png"  
            expandedName = ".png";  
        } else if (uploadContentType.equals("image/gif")) {  
            expandedName = ".gif";  
        } else if (uploadContentType.equals("image/bmp")) {  
            expandedName = ".bmp";  
        } else {  
            out.println("<script type=\"text/javascript\">");  
            out.println("window.parent.CKEDITOR.tools.callFunction(" + callback  
                    + ",''," + "'File format is not correct(must end with .jpg/.gif/.bmp/.png)');");  
            out.println("</script>");  
            return null;  
        }  
        InputStream is = new FileInputStream(fileClientName);  
        //图片上传路径  
        String uploadPath = bundle.getString("notice.uploadPath");
        uploadPath = uploadPath.trim() ;
        String fileName = java.util.UUID.randomUUID().toString(); // 采用时间+UUID的方式随即命名  
        fileName += expandedName;  
        File file = new File(uploadPath);  
        if (!file.exists()) { // 如果路径不存在，创建  
            file.mkdirs();  
        }  
        File toFile = new File(uploadPath, fileName);  
        OutputStream os = new FileOutputStream(toFile);  
        byte[] buffer = new byte[1024];  
        int length = 0;  
        while ((length = is.read(buffer)) > 0) {  
            os.write(buffer, 0, length);  
        }  
        is.close();  
        os.close();  
        String noticeimg = bundle.getString("notice.noticeimg") ;
        noticeimg = noticeimg.trim();
        // 返回"图像"选项卡并显示图片  request.getContextPath()为web项目名   
        out.println("<script type=\"text/javascript\">");  
        out.println("window.parent.CKEDITOR.tools.callFunction("+callback+ ",'"+noticeimg + fileName + "','')"); 
        out.println("</script>");  
        return null;  
	}

	@RequestMapping(value = "v2_commit", method = RequestMethod.POST)
	public String commit(@RequestParam(value = "notice_id", required = false) Long notice_id,@Valid Notice notice, RedirectAttributes redirectAttributes,HttpServletRequest request ) {
		String noticeDes = request.getParameter("financial.bz") ;
		String noticeTitle = request.getParameter("noticeTitle") ;
		String status = request.getParameter("status") ;
		if(status.equals("1")){
			noticeService.updateAll();
		}
		notice.setNoticeDes(noticeDes);
		notice.setNoticeTitle(noticeTitle);
		notice.setNoticeType("");
		notice.setStatus(status);
		notice.setCreateTime(new Date());
		noticeService.saveNotice(notice) ;
		return "notice/noticeList";
	}

	@RequestMapping(value = "v2_update/{id}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") Long id, Model model) {
		model.addAttribute("notice", noticeService.findById(id) );
		model.addAttribute("action", "update");
		return "notice/noticeForm";
	}
	@RequestMapping(value = "findById/{id}", method = RequestMethod.POST)
	public void loadDetail(@PathVariable("id") Long id, HttpServletResponse response) {
		try {
			Notice notice  = noticeService.findById(id);
			JSONObject json = new JSONObject();
			json.put("notice", notice);
			response.getWriter().print(json);
		} catch (Exception e) {
			log.error("error.", e);
		}
	}


	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(@RequestParam(value = "notice_id", required = false) Long notice_id,@Valid Notice notice, RedirectAttributes redirectAttributes,HttpServletRequest request ) {
		String noticeDes = request.getParameter("financial.bz") ;
		String noticeTitle = request.getParameter("noticeTitle") ;
		String status = request.getParameter("status") ;
		if(status.equals("1")){
			noticeService.updateAll();
		}
		notice.setNoticeDes(noticeDes);
		notice.setNoticeTitle(noticeTitle);
		notice.setNoticeType("");
		notice.setStatus(status);
		notice.setCreateTime(new Date());
		noticeService.saveNotice(notice);
		redirectAttributes.addFlashAttribute("message", "更新公告成功");
		return "redirect:/notice/v2_show";
	}

	@RequestMapping(value = "delete/{id}")
	public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		noticeService.deleteNotice(id);
		redirectAttributes.addFlashAttribute("message", "删除公告成功");
		return "redirect:/notice/v2_show";
	}
	@RequestMapping(value = "top/{id}")
	public String top(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		noticeService.updateAll();
		noticeService.updateById(id);
		redirectAttributes.addFlashAttribute("message", "置顶公告成功");
		return "redirect:/notice/v2_show";
	}

	/**
	 * 获取当前登陆人是否阅读置顶消息
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "ajaxGetNotice")
	@ResponseBody
	public void ajaxGetNotice(@RequestParam String jobuuid,HttpServletResponse response) {
		JSONObject json=null;
		PrintWriter out=null;
		try {
			out=response.getWriter();
			json=new JSONObject();
			Notice notice = null;
			List<Notice> notices = this.noticeService.findByJobuuidNoReaderNotice(jobuuid) ;
			if(null == notices||notices.size()<=0){
				//查找置顶的公告
				List<Notice> noticeList = noticeService.findByStatus("1") ;
				if(null!=noticeList&&noticeList.size()>0){
					json.put("notice",noticeList.get(0)) ;
					json.put("status", "no") ;
				}else{
					json.put("status", "readed") ;
				}
			}else{
				json.put("status", "readed") ;
			}
			out.print(json.toString());
		} catch (Exception e) {
			log.error("error",e);
		}
	}
	@RequestMapping(value = "findById2/{id}", method = RequestMethod.POST)
	public void loadDetail2(@PathVariable("id") Long id,ServletRequest request, HttpServletResponse response) {
		try {
			Notice notice  = noticeService.findById(id);
			String jobuuid = request.getParameter("jobuuid") ;
			NoticeReader noticeReader = new NoticeReader() ;
			noticeReader.setNoticeId(String.valueOf(id));
			noticeReader.setJobuuid(jobuuid);
			this.noticeService.saveNoticeReader(noticeReader);
			JSONObject json = new JSONObject();
			json.put("notice", notice);
			response.getWriter().print(json);
		} catch (Exception e) {
			log.error("error.", e);
		}
	}
	
}